package com.property;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.Window;

import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteLine;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;

import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.property.adapter.RouteAdapter;
import com.property.overlay.MyBikingRouteOverlay;
import com.property.overlay.MyDrivingRouteOverlay;
import com.property.overlay.MyTransitRouteOverlay;
import com.property.overlay.MyWalkingRouteOverlay;
import com.property.overlayutil.BikingRouteOverlay;
import com.property.overlayutil.DrivingRouteOverlay;
import com.property.overlayutil.OverlayManager;
import com.property.overlayutil.TransitRouteOverlay;
import com.property.overlayutil.WalkingRouteOverlay;

import java.util.List;

/**
 * 线路规划
 */
public class RoutePlanActivity extends Activity implements BaiduMap.OnMapClickListener, OnGetRoutePlanResultListener, View.OnClickListener {
    private Context context = this;

    RouteLine route = null;
    OverlayManager routeOverlay = null;

    MapView mMapView = null;    // 地图View
    BaiduMap mBaidumap = null;
    // 搜索相关
    RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用
    WalkingRouteResult nowResultwalk = null;
    BikingRouteResult nowResultbike = null;
    TransitRouteResult nowResultransit = null;
    DrivingRouteResult nowResultdrive = null;

    PlanNode stNode;
    PlanNode enNode;

    TextView drive;
    TextView transit;
    TextView walk;
    TextView bike;
    private RouteAdapter adapter;
    private RecyclerView route_recycler;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.routeplan_main);
        initView();
    }

    private void initView() {
        drive = findViewById(R.id.drive);
        transit = findViewById(R.id.transit);
        walk = findViewById(R.id.walk);
        bike = findViewById(R.id.bike);


        route_recycler = findViewById(R.id.route_recycler);
        route_recycler.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        adapter = new RouteAdapter(context);

        CharSequence titleLable = "路线规划功能";
        setTitle(titleLable);
        // 初始化地图
        mMapView = findViewById(R.id.map);
        mBaidumap = mMapView.getMap();
        // 地图点击事件处理
        mBaidumap.setOnMapClickListener(this);
        // 初始化搜索模块，注册事件监听
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);

        stNode = PlanNode.withLocation(new LatLng(22.576696, 114.06779));
        enNode = PlanNode.withLocation(new LatLng(22.615102391232636, 114.03552767540026));

//        stNode = PlanNode.withCityNameAndPlaceName("北京", "西二旗地铁站");
//        enNode = PlanNode.withCityNameAndPlaceName("北京", "百度科技园");


        mSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));


        drive.setOnClickListener(this);
        transit.setOnClickListener(this);
        walk.setOnClickListener(this);
        bike.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 重置浏览节点的路线数据
        route = null;
        mBaidumap.clear();

        selectView(false, drive);
        selectView(false, transit);
        selectView(false, walk);
        selectView(false, bike);

        // 实际使用中请对起点终点城市进行正确的设定
        if (v.getId() == R.id.drive) {
            mSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
            selectView(true, drive);
        } else if (v.getId() == R.id.transit) {
            mSearch.transitSearch((new TransitRoutePlanOption()).from(stNode).city("深圳").to(enNode));
            selectView(true, transit);
        } else if (v.getId() == R.id.walk) {
            mSearch.walkingSearch((new WalkingRoutePlanOption()).from(stNode).to(enNode));
            selectView(true, walk);
        } else if (v.getId() == R.id.bike) {
            mSearch.bikingSearch((new BikingRoutePlanOption()).from(stNode).to(enNode));
            selectView(true, bike);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    /**
     * @param result
     */
    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(context, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("提示");
            builder.setMessage("检索地址有歧义，请重新设置。\n可通过getSuggestAddrInfo()接口获得建议查询信息");
            builder.setPositiveButton("确认", (dialog, which) -> dialog.dismiss());
            builder.create().show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            if (result.getRouteLines().size() >= 1) {
                try {
                    // 直接显示
                    route_recycler.setVisibility(View.GONE);
                    route = result.getRouteLines().get(0);
                    mBaidumap.clear();
                    WalkingRouteOverlay overlay = new MyWalkingRouteOverlay(mBaidumap);
                    mBaidumap.setOnMarkerClickListener(overlay);
                    routeOverlay = overlay;
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();

                    if (result.getRouteLines().size() >= 1) {
                        nowResultwalk = result;
                        route_recycler.setVisibility(View.VISIBLE);
                        adapter.setDatas(result.getRouteLines(), RouteAdapter.Type.WALKING_ROUTE);
                        route_recycler.setAdapter(adapter);
                        adapter.setItemClickListener((view, position) -> {
                            route = nowResultwalk.getRouteLines().get(position);
                            mBaidumap.clear();
                            WalkingRouteOverlay overlay1 = new MyWalkingRouteOverlay(mBaidumap);
                            mBaidumap.setOnMarkerClickListener(overlay1);
                            routeOverlay = overlay1;
                            overlay1.setData(nowResultwalk.getRouteLines().get(position));
                            overlay1.addToMap();
                            overlay1.zoomToSpan();
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("route result", "结果数<0");
                return;
            }
        }

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult result) {

        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(context, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            if (result.getRouteLines().size() >= 1) {
                try {
                    // 直接显示
                    route_recycler.setVisibility(View.GONE);
                    route = result.getRouteLines().get(0);
                    mBaidumap.clear();
                    TransitRouteOverlay overlay = new MyTransitRouteOverlay(mBaidumap);
                    mBaidumap.setOnMarkerClickListener(overlay);
                    routeOverlay = overlay;
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();

                    if (result.getRouteLines().size() >= 1) {
                        route_recycler.setVisibility(View.VISIBLE);
                        nowResultransit = result;
                        adapter.setDatas(result.getRouteLines(), RouteAdapter.Type.TRANSIT_ROUTE);
                        route_recycler.setAdapter(adapter);
                        adapter.setItemClickListener((view, position) -> {
                            route = nowResultransit.getRouteLines().get(position);
                            mBaidumap.clear();
                            TransitRouteOverlay overlay1 = new MyTransitRouteOverlay(mBaidumap);
                            mBaidumap.setOnMarkerClickListener(overlay1);
                            routeOverlay = overlay1;
                            overlay1.setData(nowResultransit.getRouteLines().get(position));
                            overlay1.addToMap();
                            overlay1.zoomToSpan();
                        });
                        mMapView.onResume();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("route result", "结果数<0");
                return;
            }
        }
    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult result) {
    }


    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(context, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {

            if (result.getRouteLines().size() > 1) {
                try {
                    route_recycler.setVisibility(View.GONE);
                    route = result.getRouteLines().get(0);
                    mBaidumap.clear();
                    DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaidumap);

                    routeOverlay = overlay;
                    mBaidumap.setOnMarkerClickListener(overlay);
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();

                    if (result.getRouteLines().size() >= 1) {
                        route_recycler.setVisibility(View.VISIBLE);
                        nowResultdrive = result;
                        adapter.setDatas(result.getRouteLines(), RouteAdapter.Type.DRIVING_ROUTE);
                        route_recycler.setAdapter(adapter);
                        adapter.setItemClickListener((view, position) -> {
                            route = nowResultdrive.getRouteLines().get(position);
                            mBaidumap.clear();
                            DrivingRouteOverlay overlay1 = new MyDrivingRouteOverlay(mBaidumap);
                            mBaidumap.setOnMarkerClickListener(overlay1);
                            routeOverlay = overlay1;
                            overlay1.setData(nowResultdrive.getRouteLines().get(position));
                            overlay1.addToMap();
                            overlay1.zoomToSpan();

                            mMapView.refreshDrawableState();
                        });
                        mMapView.onResume();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("route result", "结果数<0");
                return;
            }
        }
    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(context, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("提示");
            builder.setMessage("检索地址有歧义，请重新设置。\n可通过getSuggestAddrInfo()接口获得建议查询信息");
            builder.setPositiveButton("确认", (dialog, which) -> dialog.dismiss());
            builder.create().show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            if (result.getRouteLines().size() >= 1) {
                try {
                    route_recycler.setVisibility(View.GONE);
                    route = result.getRouteLines().get(0);
                    mBaidumap.clear();
                    BikingRouteOverlay overlay = new MyBikingRouteOverlay(mBaidumap);
                    routeOverlay = overlay;
                    mBaidumap.setOnMarkerClickListener(overlay);
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();

                    if (result.getRouteLines().size() >= 1) {
                        route_recycler.setVisibility(View.VISIBLE);
                        nowResultbike = result;
                        adapter.setDatas(result.getRouteLines(), RouteAdapter.Type.BIKING_ROUTE);
                        route_recycler.setAdapter(adapter);
                        adapter.setItemClickListener((view, position) -> {
                            route = nowResultbike.getRouteLines().get(position);
                            mBaidumap.clear();
                            BikingRouteOverlay overlay1 = new MyBikingRouteOverlay(mBaidumap);
                            mBaidumap.setOnMarkerClickListener(overlay1);
                            routeOverlay = overlay1;
                            overlay1.setData(nowResultbike.getRouteLines().get(position));
                            overlay1.addToMap();
                            overlay1.zoomToSpan();
                        });
                        mMapView.onResume();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("route result", "结果数<0");
                return;
            }
        }
    }


    @Override
    public void onMapClick(LatLng point) {
        mBaidumap.hideInfoWindow();
    }

    @Override
    public boolean onMapPoiClick(MapPoi poi) {
        return false;
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mSearch != null) {
            mSearch.destroy();
        }
        mMapView.onDestroy();
        super.onDestroy();
    }


    private void selectView(Boolean isSelect, TextView view) {
        if (isSelect) {
            view.setTextColor(Color.parseColor("#FFFFFF"));
            view.setBackgroundColor(Color.parseColor("#03a9f4"));
        } else {
            view.setTextColor(Color.parseColor("#333333"));
            view.setBackgroundColor(Color.parseColor("#FFFFFF"));
        }
    }
}

